#!/usr/bin/env python

import os
import pyglet
from pyglet.gl import *
from lib.Hero import Hero
from lib import Util
from lib.Mobile import ScriptedMobile
from lib import Behavior
from lib import CAConfig
from lib import Map
from lib import UI

# go go speed racer
try:
    import psyco
    psyco.full()
except ImportError:
    pass

class CollectionAgencyWindow(pyglet.window.Window):
    event_handler_names  = ('on_key_press','on_key_release')
    
    def __init__(self, *args, **kwargs):
        super(CollectionAgencyWindow, self).__init__(*args, **kwargs)
        self.viewport = args[0],args[1]
        self.set_caption("Collection Agency")
        # Load the game font
        pyglet.resource.add_font('Inconsolata.otf')
        self.ft = pyglet.font.load('Inconsolata',16,dpi=96)
        # Allow transparency
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        # ui layer
        self.ui = {}
            
    def register_mobiles(self,mobiles):
        """
        Registers event handlers for all mobiles.
        Question: Does this even make sense?
        """
        for m in mobiles:
            [self.push_handlers( getattr(m, eh) )
                for eh in self.event_handler_names if hasattr( m, eh )]

def get_all_dirs( path ):
    '''Scans all directories for resources and adds them to the resource path
    and re-indexes the resorce cache afterwards.'''
    for f in os.listdir( path ):
        f = os.path.join( path, f )
        if os.path.isdir( f ) and not f.endswith(".svn"):
            pyglet.resource.path.append( f )
            get_all_dirs( f )
    pyglet.resource.reindex()

def main():
    CAConfig.map_size = width,height = 1280, 1280 # pick the size of the map
    CAConfig.viewport = v_w,v_h      = 640, 480   # pick the size of the viewport

    get_all_dirs( os.path.abspath(pyglet.resource.get_script_home()) )

    win = CollectionAgencyWindow(v_w,v_h)

    # store the window object in the global configuration
    CAConfig.window = win
    
    #Get the image used for the hero character and place him
    #facing forward
    win.hero = Hero('Hero.png')

    # try out something
    doppleganger = ScriptedMobile('Hero.png',behavior=Behavior.follow(win.hero))
    doppleganger.acceleration = 2

    win.register_mobiles([win.hero])
    
    # parse all the map stuff
    Map.boot()
    
    static_map = Map.StaticMap('testing2.js')
    background = static_map.background

    win.ui['status_bar'] = UI.StatusBar()

    def process( dt, desired_interval ):
        # Determine where to start drawing from
        x,y = win.hero.update()
        
        # The background is the same size as scratch so just draw it
        background.get_region(x,y,v_w,v_h).blit(0,0)
        
        win.hero.draw((x,y))
        doppleganger.update((x,y))
        if win.hero.collides(doppleganger):
            pass
            #print "Collision!"
        
        # update UI if it is there
        for ui in win.ui.values():
            ui.draw()
    
    pyglet.clock.schedule(process, 1/30.0)

    pyglet.app.run()

if __name__ == "__main__":
    main()
